<template>
  <div class="text-input-field" :class="getIndentClass(modelValue.alignment)">
    <!-- 字段名称 -->
    <div class="field-name-container">
      <span v-if="modelValue.prefixSymbol && modelValue.prefixSymbol !== 'none'" class="prefix-symbol">
        {{ getPrefixSymbol() }}
      </span>
      <el-input 
        v-model="modelValue.fieldName" 
        placeholder="字段名称"
        class="field-name-input"
        :class="{ 'bold-text': modelValue.isBold, 'nowrap': shouldNowrap }"
        :style="{ width: fieldNameDynamicWidth }"
        type="textarea"
        :autosize="{ minRows: 1, maxRows: 6 }"
        @input="updateFieldName"
        @change="handleFieldNameChange"
      />
    </div>
    
    <!-- 文本输入格式显示 -->
    <div class="text-input-display">
      <div class="input-segments">
        <template v-for="(segment, index) in inputSegments" :key="index">
          <!-- 数字段 -->
          <div v-if="segment.type === 'digit'" class="digit-segment">
            <div class="digit-placeholder">
              <span class="underscores"></span>
            </div>
          </div>
          <!-- 小数点 -->
          <div v-else-if="segment.type === 'decimal'" class="decimal-segment">
            <span class="decimal-point">.</span>
          </div>
        </template>
      </div>
      
      <!-- 后缀显示 -->
      <el-input 
        v-if="modelValue.suffix !== undefined" 
        v-model="modelValue.suffix" 
        class="field-name-input"
        :style="{ width: getSuffixWidth() }"
        placeholder="后缀"
        @input="updateSuffix"
      />
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
    default: () => ({
      value: '',
      fieldName: '',
      fieldFormat: '0',
      suffix: '',
      alignment: 'indent-0',
      prefixSymbol: '',
      isBold: false
    })
  }
})

const emit = defineEmits(['update:modelValue'])

// 更新字段名称
const updateFieldName = (value) => {
  emit('update:modelValue', {
    ...props.modelValue,
    fieldName: value
  })
}

const updateSuffix = (value) => {
  emit('update:modelValue', {
    ...props.modelValue,
    suffix: value
  })
}

// 解析字段格式
const inputSegments = computed(() => {
  const format = props.modelValue.fieldFormat || '0'
  const segments = []
  
  // 解析格式，例如 "3.1" -> 3个数字位 + 小数点 + 1个小数位
  if (format.includes('.')) {
    const [integerPart, decimalPart] = format.split('.')
    const integerDigits = parseInt(integerPart) || 0
    const decimalDigits = parseInt(decimalPart) || 0
    
    // 添加整数位
    for (let i = 0; i < integerDigits; i++) {
      segments.push({ type: 'digit' })
    }
    
    // 添加小数点
    if (decimalDigits > 0) {
      segments.push({ type: 'decimal' })
    }
    
    // 添加小数位
    for (let i = 0; i < decimalDigits; i++) {
      segments.push({ type: 'digit' })
    }
  } else {
    // 只有整数位
    const digits = parseInt(format) || 0
    for (let i = 0; i < digits; i++) {
      segments.push({ type: 'digit' })
    }
  }
  
  return segments
})

// 动态宽度（短文本时更短，最长到 130 字符宽度）
const fieldNameDynamicWidth = computed(() => {
  const text = props.modelValue?.fieldName || ''
  const minPx = 140
  const maxPx = 720
  const padding = 24
  const measured = getTextWidth(text || '字段名称', '14px', 'Arial')
  const px = Math.min(Math.max(measured + padding, minPx), maxPx)
  return `${px}px`
})

// 在可容纳范围内尽量保持单行显示，超过阈值再换行
const shouldNowrap = computed(() => {
  const text = props.modelValue?.fieldName || ''
  return text.length <= 130
})

// 获取缩进类
const getIndentClass = (alignment) => {
  const indentMap = {
    'indent-0': 'indent-0',
    'indent-1': 'indent-1',
    'indent-2': 'indent-2',
    'indent-3': 'indent-3',
    'indent-4': 'indent-4',
    'indent-5': 'indent-5'
  }
  return indentMap[alignment] || 'indent-0'
}

// 获取前缀符号
const getPrefixSymbol = () => {
  const symbolMap = {
    'dot_circle': '⏺',
    'star': '✧',
    'pointer': '☞',
    'arrow_curved': '⮚',
    'square': '⯀',
    // backward compatibility
    'triangle': '▶',
    'dot': '●',
    'wing_triangle': '▶',
    'wing_dot': '●'
  }
  return symbolMap[props.modelValue.prefixSymbol] || ''
}

// 计算文本宽度
const getTextWidth = (text, fontSize = '14px', fontFamily = 'Arial') => {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  context.font = `${fontSize} ${fontFamily}`
  return context.measureText(text).width
}

// 获取字段名称宽度
const getFieldNameWidth = () => {
  const text = props.modelValue.fieldName || '字段名称'
  const width = getTextWidth(text, '14px', 'Arial')
  return `${Math.max(width + 20, 60)}px` // 最小60px，加20px内边距
}

const getSuffixWidth = () => {
  const text = props.modelValue.suffix || '后缀'
  const width = getTextWidth(text, '14px', 'Arial')
  return `${Math.max(width + 20, 60)}px` // 最小60px，加20px内边距
}

const handleFieldNameChange = () => {
  // trim 去除空格
  props.modelValue.fieldName = props.modelValue.fieldName.trim();
};
</script>

<style lang="scss" scoped>
@import '@/assets/common-styles.scss';

.text-input-field {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: nowrap;
  
      .text-input-display {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .input-segments {
        display: flex;
        align-items: center;
        gap: 0;
        border: none;
        border-radius: 0;
        padding: 0;
        height: 20px;
        
        .digit-segment {
          position: relative;
          margin-right: 0;
          
          .digit-placeholder {
            width: 30px;
            height: 18px;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            border-bottom: 1px solid #9b9191;
            border-left: 1px solid #9b9191;
            border-right: 1px solid #9b9191;
            
            .underscores {
              font-size: 12px;
              color: #000;
              font-weight: normal;
              letter-spacing: 0.5px;
              z-index: 1;
            }
          }
        }

        .digit-segment + .digit-segment {
          margin-left: -1px;
        }
        
        .decimal-segment {
          margin: 0;
          padding: 0 4px;
          display: flex;
          align-items: center;
          position: relative;
          .decimal-point {
            font-size: 12px;
            font-weight: normal;
            color: #000;
            line-height: 1;
            z-index: 1;
          }
        }
      }
      
      .suffix-display {
        .suffix-text {
          font-size: 14px;
          color: #303133;
          font-weight: normal;
          line-height: 1;
        }
      }
    }
}

.field-name-input.nowrap :deep(textarea) {
  white-space: nowrap;   /* 尽量单行展示 */
  overflow-x: auto;      /* 超过宽度时允许横向滚动 */
  overflow-y: hidden;    /* 隐藏垂直滚动，避免高度被撑大 */
}
</style> 